﻿using System;
using System.Collections.Generic;
using System.Text;
using ilibrary.source.model;
using HtmlHelp;
using System.Collections;

namespace CHMHandler
{
    public class CHMEbook : EBook
    {
        public CHMEbook(int id, string filepath):base(id,filepath)
        {
            //on vérifie que c'est bien un fichier CHM
            if (filepath == null || System.IO.Path.GetExtension(filepath).ToLower() != ".chm")
                throw new NotSupportedException("The file " + filepath + " is not a CHM file.");

        }

        public override bool readToc(IEBookReadingHandler cB)
        {
            try
            {
                HtmlHelpSystem reader = new HtmlHelpSystem();
                reader.OpenFile(Filepath);

                if (reader.HasTableOfContents)
                {
                    string res = buildTOC(reader.TableOfContents.TOC, cB);
                    toc = "<toc>" + res + "</toc>";

                    reader.CloseAllFiles();
                    return true;
                }
                else
                {
                    reader.CloseAllFiles();
                    toc = string.Empty;//so that, we don't retry to load the toc
                    return false;
                }
            }
            catch (Exception)
            {
                toc = null;
                return false;
            }
        }

        private string buildTOC(ArrayList tocItems, IEBookReadingHandler cB)
        {
            string res = "";

            foreach (TOCItem curItem in tocItems)
            {
                res += "<tocItem>";
                res += "<topic>" + curItem.Name + "</topic>";

                if (curItem.Children.Count > 0)
                {
                    res += "<toc>";
                    res += buildTOC(curItem.Children, cB);
                    res += "</toc>";
                }

                res += "</tocItem>";
                if (cB != null)
                    cB.performReadingStep();

            }
            return res;
        }
    }
}
